from PyQt5 import QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QTreeWidgetItem,QAbstractItemView,QMenu, QAction, QMessageBox
import os,csv

from database import usedb
from projectinfo.pile_score import Ui_diag_pilescores
class pile_score_window(Ui_diag_pilescores):
    def __init__(self):
        super(pile_score_window, self).__init__()
        # 只显示关闭按钮
        self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)
        self.setupUi(self)
        self.show()
        header = [
            "序号", "桩号", "里程", "龄期",
            "深度", "硬度状态", "状态得分", "标贯击数", "杆长折减击数", "龄期折减击数",
            "标贯得分", "强度(MPa)", "折算强度(MPa)", "强度得分", "每层得分", "上下得分",
            "综合得分", "综合评定"
        ]
        self.tw_pilescores.setColumnCount(len(header))
        self.tw_pilescores.setHeaderLabels(header)
        header = self.tw_pilescores.header()
        header.setDefaultAlignment(QtCore.Qt.AlignCenter)
        dir_proj = os.path.join(usedb.cur_path, usedb.cur_proj)
        csv_projinfo = os.path.join(dir_proj, f'{usedb.cur_proj}综合质量评分（表一）.csv')
        with open(csv_projinfo, 'r', newline='',encoding='utf-8') as csvfile:
            reader=csv.reader(csvfile)
            headerrow=next(reader)
            nums=[]
            for row in reader:
                nums.append(row[0])
        csv_pile = os.path.join(dir_proj, f'{usedb.cur_proj}试验成果及得分表（表三）.csv')
        prenum,prepilenum='',''
        with open(csv_pile, 'r', newline='',encoding='utf-8') as csvfile:
            reader=csv.reader(csvfile)
            headerrow=next(reader)
            header_length=len(headerrow)
            try:
                j=0
                for row in reader:
                    pilenum = row[1]
                    if pilenum != prepilenum:
                        num = nums[j]
                        j += 1
                        root = QTreeWidgetItem(self.tw_pilescores)
                        root.setText(0, num)
                        root.setText(1, pilenum)
                        root.setTextAlignment(0, Qt.AlignCenter)
                        root.setTextAlignment(1, Qt.AlignCenter)
                        self.tw_pilescores.addTopLevelItem(root)
                        prepilenum = pilenum
                    child = QTreeWidgetItem(root)
                    for i in range(2, header_length ):
                        child.setText(i, row[i])
                        child.setTextAlignment(i, Qt.AlignCenter)
            except StopIteration:
                print("End of file reached.")
        # 设置treewidget格式
        for column in range(self.tw_pilescores.columnCount()):
            self.tw_pilescores.resizeColumnToContents(column)
        self.tw_pilescores.setColumnWidth(1, 70)
        self.tw_pilescores.setColumnWidth(2, 70)
        self.tw_pilescores.setColumnWidth(4, 100)
        self.tw_pilescores.setSortingEnabled(False)
        self.tw_pilescores.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tw_pilescores.setAlternatingRowColors(True)
        # 创建上下文菜单
        self.context_menu = QMenu()

        # 添加“删除根节点”动作
        delete_root_action = QAction("删除桩根节点", self)
        delete_root_action.triggered.connect(self.delete_selected_root_node)
        self.context_menu.addAction(delete_root_action)

        # 连接鼠标事件
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_context_menu)

    def show_context_menu(self, pos):
        """显示上下文菜单"""
        try:
            # 检查pos的有效性，确保它是一个期望的坐标类型（这里假设是Qt的坐标类型）
            if not isinstance(pos, QtCore.QPoint):
                raise ValueError("pos必须是一个QtCore.QPoint类型")

            selected_item = self.tw_pilescores.currentItem()
            if selected_item is not None:
                # 检查所选项目是否为根节点
                if not selected_item.parent():
                    # 检查pos是否在视图范围内
                    viewport_rect = self.tw_pilescores.viewport().geometry()
                    global_pos = self.tw_pilescores.viewport().mapToGlobal(pos)
                    if viewport_rect.contains(global_pos):
                        self.context_menu.popup(global_pos)
                    else:
                        print("警告：pos位于视图范围之外")
                else:
                    print("所选项目不是根节点")
            else:
                print("没有选中的项目")
        except ValueError as e:
            print(f"错误：{e}")
        except Exception as e:
            # 捕获其他潜在异常，确保程序健壮性
            print(f"未知错误：{e}")
    def delete_selected_root_node(self):
        """处理删除根节点的逻辑"""
        selected_item = self.tw_pilescores.currentItem()
        if selected_item and not selected_item.parent():  # 确保仍选中根节点
            msg_box = QMessageBox.question(
                self,
                "确认删除",
                f"是否删除根节点 '{selected_item.text(0)}'？只是不显示，并不会删除数据",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            if msg_box == QMessageBox.Yes:
                self.tw_pilescores.takeTopLevelItem(self.tw_pilescores.indexOfTopLevelItem(selected_item))  # 删除根节点



